#!/usr/bin/env python
'''
DocIndexer PDF parser.
'''
from abstract_parser import AbstractParser
from common import APP_DIR, EDocIndexer, short_path, shell_escape
import os

class Parser(AbstractParser):

    description = 'Xpdf document parser'
    mime_types = ['application/xpdf']

    def __init__(self):
        '''Check all parser resouces are available, throw error if not.'''
        if not self.isused():
            return
        if os.name == 'nt':
            self.pdftotext = os.path.abspath(os.path.join(APP_DIR,'xpdf','pdftotext.exe'))
            if not os.path.isfile(self.pdftotext):
                raise EDocIndexer, 'pdftotext required to build indexes'

    def text(self,filename):
        try:
            # Use short file names as the Windows command interpreter does not
            # like multiple quoted paths.
            if os.name == 'nt':
                cmd = short_path(self.pdftotext) + ' -eol unix ' \
                    + short_path(filename) + ' -'
            else:
                cmd = 'pdftotext -eol unix "%s" -' %  shell_escape(filename)
            f = os.popen(cmd)
            text = f.read()
            err = f.close()
            if err is not None:
                raise EDocIndexer,'non-zero pdftotext exit status %d' % err
        except EDocIndexer:
            raise
        except:
            raise EDocIndexer,'unable to execute pdftotext'
        return self.unicode(text)


if __name__ == '__main__':
    Parser.test()

# vim: ts=4 sw=4:
